//和用户相关的状态管理

import {createSlice} from '@reduxjs/toolkit'
import { removeToken, request } from '../../utils';
import { getToken,setToken as _setToken } from '../../utils';
import {loginApi,getUserInfo} from '@/apis/user'


const userStore = createSlice({
    name:'user',
    //声明数据状态
    initialState:{
        token:getToken('token_key')||'',
        userInfo:{}
    },
    //同步修改方法
    reducers:{
        setToken(state,action){
            state.token = action.payload
            //localstorage存一份数据
            _setToken(action.payload)
        },
        setUserInfo(state,action){
            state.userInfo = action.payload
        },
        clearUserInfo(state){
            state.token = ''
            state.userInfo={}
            removeToken()
        }
    }
})

//解构出actionCreater
const {setToken,setUserInfo,clearUserInfo} = userStore.actions;

//获取reducer函数
const userReducer =userStore.reducer;

//异步方法完成登录获取token
const fetchLogin = (loginForm) =>{
    return async(dispatch)=>{
        const res = await loginApi(loginForm)
        dispatch(setToken(res.data.token))
    }
}

//获取个人用户信息的异步方法
const fetchUserInfo = () =>{
    return async(dispatch)=>{
        const res = await getUserInfo()
        dispatch(setUserInfo(res.data))   
    }
}


export {fetchLogin,fetchUserInfo,setToken,clearUserInfo}

export default userReducer;